﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml.Serialization;

namespace EQEmu.Database
{
    public static class Functions
    {
        public static double HeadingToDegrees(double heading)
        {
            return heading / 256 * 360;
        }

        public static double DegreesToHeading(double degrees)
        {
            return degrees / 360 * 256;
        }

        public static double LookAt(double myX,double myY,double myZ,double x,double y,double z)
        {
            double a = x - myX;
            double b = y - myY;
            double degrees = Math.Atan(b / a) * 180 / Math.PI;

            if (a == 0)
            {
                if (b > 0) degrees = 45.0;
                else if (b < 0) degrees = 270.0;
                else degrees = 0.0;
            }
            else if (b == 0)
            {
                if (a > 0) degrees = 0.0;
                else if (a < 0) degrees = 180.0;
                else degrees = 0.0;
            }
            else
            {
                if (a > 0)
                {
                    if (b > 0)
                    {
                        //quadrant 1                   
                        degrees = (90 - degrees) % 360;
                    }
                    else if (b < 0)
                    {
                        //quadrant 4
                        degrees = (90 - degrees) % 360;
                    }
                }
                else
                {
                    if (b > 0)
                    {
                        //quadrant 2
                        degrees = (270 - degrees) % 360;
                    }
                    else
                    {
                        //quadrant 3
                        //degrees = (180 + degrees) % 360;
                        degrees = (270 - degrees) % 360;
                    }
                }
            }

            return DegreesToHeading(degrees);
        }
    }
}

namespace EQEmu.Database.Extensions
{
    public static class SerializationExtensions
    {
        public static void ToXmlFile(this object me, string file)
        {
            using (var stream = new FileStream(file, FileMode.Create))
            {
                var serializer = new XmlSerializer(me.GetType());
                serializer.Serialize(stream, me);
            }
        }

        public static object FromXmlFile<T>(string file)
        {
            using (var stream = new FileStream(file, FileMode.Open))
            {
                var serializer = new XmlSerializer(typeof(T));
                return serializer.Deserialize(stream);
            }
        }
    }
}
